<template>
  <Form ref="form" class="xtx-form" tag="form" autocomplete="off">
    <Field             tag="div"
            class="xtx-form-item"
            v-slot="{errors}"
            rules="required|username"
            name="用户名称">
      <div class="field">
        <i class="icon iconfont icon-zhanghao"></i>
        <input name="account" v-model="form.account" :class="{err:errors[0]}" class="input" type="text" placeholder="请输入用户名" />
      </div>
      <div class="error" v-if="errors[0]">{{errors[0]}}</div>
    </Field>
    <Field  tag="div"
            class="xtx-form-item"
            v-slot="{errors}"
            rules="required|mobile"
            name="手机号码"
            ref="mobile">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <input name="mobile" v-model="form.mobile" :class="{err:errors[0]}" class="input" type="text" placeholder="请输入手机号" />
      </div>
      <div class="error" v-if="errors[0]">{{errors[0]}}</div>
    </Field>
    <Field tag="div"
            class="xtx-form-item"
            v-slot="{errors}"
            rules="required|code"
            name="验证码">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <input name="code" v-model="form.code" :class="{err:errors[0]}" class="input" type="text" placeholder="请输入验证码" />
        <span @click="send()" class="code">
          {{duration===0?'发送验证码':`${duration}秒后发送`}}
        </span>
      </div>
      <div class="error" v-if="errors[0]">{{errors[0]}}</div>
    </Field>
    <Field tag="div"
            class="xtx-form-item"
            v-slot="{errors}"
            rules="required|password:@confirm"
            name="密码">
      <div class="field">
        <i class="icon iconfont icon-suo"></i>
        <input name="password" v-model="form.password" :class="{err:errors[0]}" class="input" type="password" placeholder="请输入密码" />
      </div>
      <div class="error" v-if="errors[0]">{{errors[0]}}</div>
    </Field>
    <Field tag="div"
            class="xtx-form-item"
            v-slot="{errors}"
            rules="required"
            vid="confirm"
            name="确认密码">
      <div class="field">
        <i class="icon iconfont icon-suo"></i>
        <input name="rePassword" v-model="form.rePassword" :class="{err:errors[0]}" class="input" type="password" placeholder="请确认密码" />
      </div>
      <div class="error" v-if="errors[0]">{{errors[0]}}</div>
    </Field>
    <a @click="submit()" href="javascript:;" class="submit">立即提交</a>
  </Form>
</template>

<script>
import { extend, ValidationProvider, ValidationObserver, configure } from 'vee-validate'
import { required } from 'vee-validate/dist/rules'
import { mapMutations, mapState } from 'vuex'
import request from '@/utils/request'
configure({ enent: 'blur' })
// 必填
extend('required', {
  ...required,
  message: '请输入{_field_}'
})
// 用户名
extend('username', {
  validate: async (value) => {
    // 校验格式
    if (value.length > 20) {
      return '用户名称是20个字以内'
    }
    // 校验是否存在
    const { data } = await request.get(`register/check?account=${value}`)
    if (data.result) {
      return '用户名已存在，请换一个'
    }
    return true
  }
})
// 手机号
extend('mobile', {
  validate: (value) => {
    // 校验格式
    if (!/^1[3-9]\d{9}$/.test(value)) {
      return '手机号格式不正确'
    }
    return true
  }
})
// 手机号
extend('code', {
  validate: (value) => {
    // 校验格式
    if (!/^\d{6}$/.test(value)) {
      return '验证码6个数字'
    }
    return true
  }
})
// 密码
extend('password', {
  params: ['target'],
  validate: (value, { target }) => {
    // 校验格式
    if (!/^\w{6,20}$/.test(value)) {
      return '密码是6-20个字符'
    }
    if (value !== target) {
      return '两次输入的密码不一致'
    }
    return true
  }
})
export default {
  name: 'CallbackPatch',
  components: { Form: ValidationObserver, Field: ValidationProvider },
  props: ['openId'],
  data () {
    return {
      form: {
        account: '',
        mobile: '',
        code: '',
        password: '',
        rePassword: ''
      },
      duration: 0
    }
  },
  computed: {
    ...mapState('user', ['returnUrl'])
  },
  methods: {
    ...mapMutations('user', ['setUser']),
    async submit () {
      const valid = await this.$refs.form.validate()
      if (valid) {
        try {
          const { data } = await this.$http.post('/login/social/' + this.openId + '/complement', this.form)
          this.setUser(data.result)
          this.$router.push(this.returnUrl || '/')
          this.$message({ message: '完善信息成功', type: 'success' })
        } catch (e) {
          this.$message({ message: '完善信息失败', type: 'error' })
        }
      }
    },
    async send () {
      const { valid } = await this.$refs.mobile.validate()
      if (valid === true) {
        if (this.duration > 0) return
        await this.$http.get('/register/code', { mobile: this.form.mobile })
        this.duration = 60
        clearInterval(this.timer)
        this.timer = window.setInterval(() => {
          this.duration--
          if (this.duration === 0) clearInterval(this.timer)
        }, 1000)
      }
    }
  }
}
</script>

<style scoped lang='less'>
// 表单
.xtx-form {
  padding: 50px 0;
  &-item {
    display: flex;
    align-items: center;
    width: 700px;
    margin: 0 auto;
    padding-bottom: 25px;
    .label {
      width: 180px;
      padding-right: 10px;
      text-align: right;
      color: #999;
      ~ .field {
        margin-left: 0;
      }
    }
    .field {
      width: 320px;
      height: 50px;
      position: relative;
      margin-left: 190px;
      .icon {
        position: absolute;
        left: 0;
        top: 0;
        width: 40px;
        height: 50px;
        text-align: center;
        line-height: 50px;
        color: #999;
        ~ .input {
          padding-left: 40px;
        }
      }
      .input{
        border: 1px solid #e4e4e4;
        width: 320px;
        height: 50px;
        line-height: 50px;
        padding: 0 10px;
        &.err {
          border-color: @priceColor;
        }
        &:focus,&:active{
          border-color: @xtxColor;
        }
      }
    }
    .error {
      width: 180px;
      padding-left: 10px;
      color: @priceColor;
    }
  }
  .submit {
    width: 320px;
    height: 50px;
    border-radius: 4px;
    background: @xtxColor;
    height: 50px;
    line-height: 50px;
    text-align: center;
    font-size: 16px;
    color: #fff;
    display: block;
    margin: 0 auto;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
